﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using YunLuPos.Command;
using YunLuPos.DB.Service;
using YunLuPos.Entity;
using YunLuPos.Entity.Constant;
using YunLuPos.Net;

namespace YunLuPos
{
    public partial class MainForm : Form
    {
        
        private GoodsService goodsService = new GoodsService();
        private SaleOrderService orderService = new SaleOrderService();
        private SaleOrderGoodsService orderGoodsService = new SaleOrderGoodsService();
        private KeyBoardService keyBoardService = new KeyBoardService();
        private PromotionService promService = new PromotionService();
        private GroupPromotionService groupPromotionService = new GroupPromotionService();
       
        private LoginInitForm loginForm;
        public MainForm(LoginInitForm loginForm)
        {
            InitializeComponent();
            this.loginForm = loginForm;
        }

        /**
        * 窗体初始化加载
        * */
        private void MainForm_Load(object sender, EventArgs e)
        {
            //启动网络监测
            netCheckWorker.RunWorkerAsync();

            loadTouchBtn();
            CommandManager.Exec(this, Names.BarCodeFocus.ToString());
            displayStaticInfo();
            createNewOrder();

        }

        /**
       * 加载快捷方式
       * */
        void loadTouchBtn()
        {
            List<KeyBoard> btns = keyBoardService.listByHolder("主窗体");
            this.shortBar.setContent(btns);
        }

        /**
         * 条码搜索
         * */
        private void goodsInfoPanel1_CodeSearchEvent(string value, Com.GoodsInfoPanel handel)
        {
            if ((value == null || "".Equals(value)))
            {
                CommandManager.Exec(this, Names.Payment.ToString());
                return;
            }
            Goods goods = goodsService.getGoodsByCode(value);
            handel.setGoods(goods);
            if(goods != null)
            {
                //检查普通促销
                Promotion prom = promService.getPromPrice(goods.barCode);
                if (prom == null)
                {
                    orderGoodsService.addGoods(DynamicInfoHoder.currentOrder, goods);
                    //
                    Boolean b = groupPromotionService.doGroupProm(DynamicInfoHoder.currentOrder);
                }
                else
                {
                    orderGoodsService.addGoods(DynamicInfoHoder.currentOrder, goods,1,prom.promPrice,GoodsPriceSource.PROM,prom.promCode);
                }
                displayCurrentOrder();
            }
        }

        /**
         * 快捷菜单点击事件
         * 系统操作
         * */
        private void shortBar1_OptionTouchEvent(string value, Com.ShortBar handel)
        {
            CommandManager.Exec(this, Names.BarCodeFocus.ToString());
            doCommand(value);
        }


        /**
         * 主窗体键盘事件
         * 系统操作
         * */
        private void MainForm_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.D0 ||
               e.KeyCode == Keys.D1 ||
               e.KeyCode == Keys.D2 ||
               e.KeyCode == Keys.D3 ||
               e.KeyCode == Keys.D4 ||
               e.KeyCode == Keys.D5 ||
               e.KeyCode == Keys.D6 ||
               e.KeyCode == Keys.D7 ||
               e.KeyCode == Keys.D8 ||
               e.KeyCode == Keys.D9 ||
               e.KeyCode == Keys.Enter
                )
            {
                return;
            }
            if (e.KeyCode == Keys.Up)
            {
                this.goodsGrid.moveUp();
            }
            else if (e.KeyCode == Keys.Down)
            {
                this.goodsGrid.moveDown();
            }else
            {
                //Console.WriteLine(e.KeyCode);
                //按键操作方法
                doCommand(e.KeyCode.ToString());
            }
        }


        /**
         * 真实操作命令函数
         * */
        void doCommand(String keyCode)
        {
            KeyBoard kb = keyBoardService.getByKeyCode("主窗体", keyCode);
            if(kb != null)
            {
                CommandManager.Exec(this, kb.commandKey);
            }
        }

        /**
         * 显示静态信息
         * */
        void displayStaticInfo()
        {
            this.topInfoPanel1.setCommInfo(StaticInfoHoder.commInfo);
        }

        /**
         * 创建一个新的单据
         * 并将当前单据设置为上一单
         * */
        public void createNewOrder(Boolean setPre = true)
        {
            //刷新前一单
            if (setPre)
            {
                DynamicInfoHoder.preOrder = DynamicInfoHoder.currentOrder;
                displayPreOrder();
            }
            SaleOrder order = orderService.createNewOrder(StaticInfoHoder.commInfo);
            DynamicInfoHoder.currentOrder = order;
            displayCurrentOrder(false,true);
        }

        /**
         * 刷新当前单据显示信息
         * */
        public void displayCurrentOrder(Boolean fromdb = true,Boolean displayGoods = true)
        {
            SaleOrder order = DynamicInfoHoder.currentOrder;
            if (order != null && fromdb)
            {
                DynamicInfoHoder.currentOrder = orderService.getFullOrder(order.orderCode);
                order = DynamicInfoHoder.currentOrder;
            }
            if (displayGoods)
            {
                if(order.goods == null)
                {
                    this.goodsGrid.DataSource = new List<SaleOrderGoods>() ;
                }
                else
                {
                    this.goodsGrid.DataSource = order.goods;
                }
                //this.goodsGrid.CurrentCell
                //选中最后一行
                int last = this.goodsGrid.Rows.Count;
                if (last > 1)
                {
                    this.goodsGrid.CurrentCell = this.goodsGrid.Rows[last - 1].Cells[0];
                }
            }
            this.topInfoPanel1.setOrderInfo(order);
            this.paymentPanel1.setOrderInfo(order);

        }

        /**
        * 刷新前一单据显示信息
        * */
        void displayPreOrder(Boolean fromdb = true)
        {
            SaleOrder order = DynamicInfoHoder.preOrder;
            if(fromdb && order != null)
            {
                DynamicInfoHoder.preOrder = orderService.getFullOrder(order.orderCode);
                order = DynamicInfoHoder.preOrder;
            }
            this.preOrderInfoPanel1.setOrderInfo(order);
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.loginForm.Show();
        }

        public void lockPos()
        {
            loginForm.Show();
            loginForm.setLockInfo(StaticInfoHoder.commInfo.cashierCode);
            this.Hide();
        }

        /**
         * 格式化显示
         * */
        private void goodsGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {


            if(goodsGrid.Columns["disAmount"].Index == e.ColumnIndex)
            {
                if(e.Value == null)
                {
                    return;
                }
                e.Value = Double.Parse(e.Value.ToString()).ToString("F2");
            }
            if (goodsGrid.Columns["priceSource"].Index == e.ColumnIndex)
            {
                if (e.Value == null)
                {
                    return;
                }
                if (GoodsPriceSource.NORM.ToString().Equals(e.Value))
                {
                    e.Value = "正常";
                }
                if (GoodsPriceSource.VIP.ToString().Equals(e.Value))
                {
                    e.Value = "会员价";
                }
                if (GoodsPriceSource.POS.ToString().Equals(e.Value))
                {
                    e.Value = "POS变价";
                }
                if (GoodsPriceSource.PROM.ToString().Equals(e.Value))
                {
                    e.Value = "普通促销";
                }
                if (GoodsPriceSource.GROUP_PROM.ToString().Equals(e.Value))
                {
                    e.Value = "组合促销";
                }
            }

        }

        private void netCheckWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.topInfoPanel1.setNetStats(DynamicInfoHoder.netIsAlive);
        }

        private void netCheckWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                Thread.Sleep(1000);
                netCheckWorker.ReportProgress(1);
            }
        }

        /*void BarCodeEventProc(KeyBoardHook.BarCodes BarCodes)
        {
            String barCode = BarCodes.BarCode;
            if (barCode != null)
            {
                barCode = barCode.Replace("\r", "");
            }
            Console.WriteLine(barCode);
        }

        void KeyBoradEventProc(String KeyName)
        {
            Console.WriteLine(KeyName);
        }*/
    }
}
